package com.zjw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zjw.constants.SystemConstants;
import com.zjw.annotation.domain.ResponseResult;
import com.zjw.annotation.domain.dto.AddRoleDto;
import com.zjw.annotation.domain.dto.EditRoleDto;
import com.zjw.annotation.domain.entity.Role;
import com.zjw.annotation.domain.vo.PageVo;
import com.zjw.annotation.domain.vo.RoleListVo;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.mapper.RoleMapper;
import com.zjw.service.MenuService;
import com.zjw.service.RoleService;
import com.zjw.utils.BeanCopyUtils;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 角色信息表(Role)表服务实现类
 *
 * @author lkzy
 * @since 2023-12-20 13:38:19
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuService menuService;

    @Override
    public List<Role> getRolesById(Long id) {
        return roleMapper.getRolesById(id);
    }

    /**
     * 获取角色列表
     *
     * @param pageNum  页码
     * @param pageSize 页面大小
     * @param roleName 角色名称
     * @param status   地位
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult getRoleList(Long pageNum, Long pageSize, String roleName, String status) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        if (Strings.hasText(roleName)) {
            wrapper.like(Role::getRoleName, roleName);
        }
        if (Strings.hasText(status)) {
            wrapper.eq(Role::getStatus, status);
        }

        IPage<Role> page = new Page(pageNum, pageSize);
        page(page, wrapper);

        List<Role> rawList = page.getRecords();
        List<RoleListVo> res = BeanCopyUtils.copyList(rawList, RoleListVo.class);

        return ResponseResult.okResult(new PageVo(res, page.getTotal()));
    }

    /**
     * 更改角色状态 启用、停用角色
     *
     * @param roleId 角色 ID
     * @param status 地位
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult chanegRoleStatus(Long roleId, String status) {
        LambdaUpdateWrapper<Role> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Role::getId, roleId);
        wrapper.set(Role::getStatus, status);

        boolean res = update(wrapper);
        if (res) {
            return ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_INVALID_CHECK);
    }


    /**
     * 按 ID 获取角色 用于修改用户
     *
     * @param id 编号
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult getRoleById(Long id) {
        Role raw = getById(id);
        if (raw == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_INVALID_CHECK);
        }

        RoleListVo res = BeanCopyUtils.copy(raw, RoleListVo.class);
        return ResponseResult.okResult(res);
    }

    /**
     * 添加角色 并创建权限关系
     *
     * @param addRoleDto 添加角色 DTO
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult addRole(AddRoleDto addRoleDto) {
        RoleMapper mapper = getBaseMapper();
        Role role = BeanCopyUtils.copy(addRoleDto, Role.class);

        save(role);
        role.getId();
//        添加权限一对多关系
        menuService.assignRoleAuth(role.getId(), addRoleDto.getMenuIds());
        return ResponseResult.okResult();
    }


    /**
     * 更新角色
     *
     * @param editRoleDto 编辑角色 DTO
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult updateRole(EditRoleDto editRoleDto) {

//        更新角色信息
        Role role = BeanCopyUtils.copy(editRoleDto, Role.class);
        if (!updateById(role)) {
//            更新失败
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_INVALID_CHECK);
        }

//        清空角色权限
        menuService.removeRoleMenuById(role.getId());

//        授权新权限
        menuService.assignRoleAuth(role.getId(), editRoleDto.getMenuIds());

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult removeRole(List<Long> ids) {


        ids.stream().forEach(id -> {
            removeById(id);
            menuService.removeRoleMenuById(id);
            roleMapper.removeUserRoleByRoleId(id);
        });
        return ResponseResult.okResult();
    }


    @Override
    public ResponseResult getAllValidRole() {
//        查询所以状态为正常的角色
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getStatus, SystemConstants.ROLE_NORMAL);

        return ResponseResult.okResult(BeanCopyUtils.copyList(list(wrapper), RoleListVo.class));
    }
    @Override
    public List<Role> getAllValidRoleFunc() {
//        查询所以状态为正常的角色
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getStatus, SystemConstants.ROLE_NORMAL);

        return list(wrapper);
    }

    /**
     * 获取当前用户所有角色信息
     *
     * @param id 编号
     * @return {@link List}<{@link Role}>
     */
    @Override
    public List<Role> getAdminRolesById(Long id) {
        RoleMapper mapper = getBaseMapper();
        return mapper.getAdminRolesById(id);
    }


    @Override
    public void assignRolesToUserById(Long id, List<String> ids) {
        RoleMapper mapper = getBaseMapper();
        ids.stream().forEach(rid->{
            mapper.assignRoleToUserById(id, rid);
        });
    }

    @Override
    public void removeUserRoleByUserId(Long id) {
        roleMapper.removeUserRoleByUserId(id);
    }
}

